package com.lan.iot.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lan.iot.Add;
import com.lan.iot.GPSUtils;
import com.lan.iot.R;
import com.google.android.material.tabs.TabLayout;
import com.lan.iot.WetherWeb;
import com.lan.iot.adapter.MyFragmentStVpTitleAdapter;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.weather.WeatherDailyBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.HeConfig;
import com.qweather.sdk.view.QWeather;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class VPHomeFragment extends Fragment {
    String Temp_max = "";
    String Temp_min = "";
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "img";
    double lo = 116.4;
    double la = 39.9;
    public String weburl = "";
    String loca = "北京 东城";
    private String title;
    private int img;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private List<Fragment> mFragmentList;
    private List<String> titleList;
    private MyFragmentStVpTitleAdapter mStVPTitleAdapter;
    private String text_we;
    public String Temp_now;
    TextView temp_now;
    TextView temp_day;
    TextView we;
    TextView city;

    public VPHomeFragment(Context con) {
        this.cont = con;
    }

    public Context cont;

    public static VPHomeFragment newInstance(String title, int img, Context con) {
        VPHomeFragment fragment = new VPHomeFragment(con);
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, title);
        args.putInt(ARG_PARAM2, img);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取位置首先网络 ，如果网络没有站点列表，再次获取GPS获取位置
     */
    int mLatitude;
    int mLongitude;
    LocationManager mLocationManager;
    private String mBestProvider;
    Location location;

    /**
     * 设置tablayout指示器的长短
     *
     * @param tab
     */
    public void showTabTextAdapteIndicator(final TabLayout tab) {
        tab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                Class<?> tabLayout = tab.getClass();
                Field tabStrip = null;
                try {
                    tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                tabStrip.setAccessible(true);
                LinearLayout ll_tab = null;
                try {
                    ll_tab = (LinearLayout) tabStrip.get(tab);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                int maxLen = 0;
                int maxTextSize = 0;
                int tabCount = ll_tab.getChildCount();
                for (int i = 0; i < tabCount; i++) {
                    View child = ll_tab.getChildAt(i);
                    child.setPadding(0, 0, 0, 0);
                    if (child instanceof ViewGroup) {
                        ViewGroup viewGroup = (ViewGroup) child;
                        for (int j = 0; j < ll_tab.getChildCount(); j++) {
                            if (viewGroup.getChildAt(j) instanceof TextView) {
                                TextView tabTextView = (TextView) viewGroup.getChildAt(j);
                                int length = tabTextView.getText().length();
                                maxTextSize = (int) tabTextView.getTextSize() > maxTextSize ? (int) tabTextView.getTextSize() : maxTextSize;
                                maxLen = length > maxLen ? length : maxLen;
                            }
                        }

                    }

                    int margin = (tab.getWidth() / tabCount - (maxTextSize + dip2px(cont, 2)) * maxLen) / 2 - dip2px(cont, 2);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                    params.leftMargin = margin;
                    params.rightMargin = margin;
                    child.setLayoutParams(params);
                    child.invalidate();
                }


            }
        });

    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void getLocation() {
        mLatitude = 0;
        mLongitude = 0;
        //这里可以使用Application的上下文
        mLocationManager = (LocationManager) cont.getSystemService(Context.LOCATION_SERVICE);
        //如果是同时有GPS和网络定位的权限，我这里的需求精度不是很高 先使用了网络
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (cont.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && cont.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                String str[] = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
                this.requestPermissions(str, 1);
                return;
            }
        }
        location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location == null) {
            //试图请求GPS
            location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            // 到了这里说明，本地没有存储位置，需要重新获取一下
            if (location == null) {
                requestLocation();
                return;
            }
        }

        // 到这里说明当前已经获取到经纬度了，直接处理后续的转换，应用了
        lo = location.getLongitude();
        la = location.getLatitude();
        String p = new GPSUtils().getAddress(la, lo);
        if (p.indexOf("市") == -1 && p.indexOf("省") == -1) return;
        loca = p.substring(p.indexOf("省") + 1, p.indexOf("市")) + " ";
        if (p.indexOf("县") != -1) {
            loca += p.substring(p.indexOf("市") + 1, p.indexOf("县") + 1);
        } else {
            loca += p.substring(p.indexOf("市") + 1, p.indexOf("区") + 1);
        }
        city.setText(loca);
    }

    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            //权限的申请结果返回
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //已授权
                    getLocation();
                } else {
                    //未授权
                    Toast.makeText(cont, "授权被拒绝！", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case 6: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //已授权
                    Intent intent = new Intent();
                    intent.setClass(cont, Add.class);
                    startActivity(intent);
                } else {
                    //未授权
                    Toast.makeText(cont, "授权被拒！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void requestLocation() {
        // 这里只获取一次的的方法
        // 需要更新就要使用这个方法LocationManager.requestLocationUpdates（）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (cont.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && cont.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                String str[] = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
                this.requestPermissions(str, 1);
                return;
            }
        }
        mLocationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 用完将监听移除
                mLocationManager.removeUpdates(this);
                // 到这里说明当前已经获取到经纬度了，直接处理后续的转换，应用了
//                getAddress(location);
                lo = location.getLongitude();
                la = location.getLatitude();
                String p = new GPSUtils().getAddress(la, lo);
                loca = p.substring(p.indexOf("省") + 1, p.indexOf("市")) + " ";
                if (p.indexOf("县") != -1) {
                    loca += p.substring(p.indexOf("市") + 1, p.indexOf("县") + 1);
                } else {
                    loca += p.substring(p.indexOf("市") + 1, p.indexOf("区") + 1);
                }
                city.setText(loca);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        }, null);
    }

    final Handler cwjHandler = new Handler();

    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateUI();
        }
    };

    private void updateUI() {
        we.setText(text_we);
//        text_we="多云";
        if (text_we.indexOf("晴") > -1) we_now.setImageResource(R.drawable.sunny);
        if (text_we.indexOf("雨") > -1) we_now.setImageResource(R.drawable.rain);
        if (text_we.indexOf("多云") > -1) we_now.setImageResource(R.drawable.cloud);
        if (text_we.indexOf("阴") > -1) we_now.setImageResource(R.drawable.yin);
        temp_now.setText(Temp_now + "℃");
        //详细的更新
    }

    final Handler cwjHandler_a = new Handler();

    final Runnable mUpdateResults_a = new Runnable() {
        public void run() {
            updateUI_a();
        }
    };

    private void updateUI_a() {
        temp_day.setText(Temp_max + "/" + Temp_min + "℃");
        //详细的更新
    }

    private void initWeather(String loc) {
        HeConfig.init("HE2303222112361980", "cc12e01681904e30897d7718dc829c0e");
        HeConfig.switchToDevService();
        QWeather.getWeatherNow(cont, loc, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                Log.i("00", "getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                String json = new Gson().toJson(weatherBean);
                JSONObject JO = JSONObject.parseObject(json);
                String now_str = JO.getString("now");
                String basic = JO.getString("basic");
                JSONObject JO_basic = JSONObject.parseObject(basic);
                String link = JO_basic.getString("fxLink");
                weburl = link;
                System.out.println(link);
                JSONObject JO_now = JSONObject.parseObject(now_str);
                String text = JO_now.getString("text");
                String temp = JO_now.getString("temp");
                System.out.println(text + " " + temp);
                Temp_now = temp;
                text_we = text;
                cwjHandler.post(mUpdateResults);
                Log.i("000", "getWeather onSuccess: " + new Gson().toJson(weatherBean));
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    Log.i("000", "failed code: " + code);
                }
            }
        });
        QWeather.getWeather3D(cont, loc, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherDailyListener() {

            @Override
            public void onError(Throwable throwable) {
                Log.i("00", "getWeather onError: " + throwable);
            }

            @Override
            public void onSuccess(WeatherDailyBean weatherDailyBean) {
                String json = new Gson().toJson(weatherDailyBean);
                JSONObject JO = JSONObject.parseObject(json);
                String str = JO.getString("daily");


                JSONArray JO_a = JSONArray.parseArray(str);
                for (Object o : JO_a) {
                    JSONObject jsonObject = (JSONObject) o;
                    Temp_max = jsonObject.getString("tempMax");
                    Temp_min = jsonObject.getString("tempMin");

                    break;
                }
                cwjHandler_a.post(mUpdateResults_a);

                Log.i("000", "getWeather onSuccess: " + new Gson().toJson(weatherDailyBean));
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherDailyBean.getCode()) {
                    List<WeatherDailyBean.DailyBean> now = weatherDailyBean.getDaily();
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherDailyBean.getCode();
                    Log.i("000", "failed code: " + code);
                }
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            title = getArguments().getString(ARG_PARAM1);
            img = getArguments().getInt(ARG_PARAM2);
        }
    }

    public void tianqiweb(View view) {

    }

    public void requestper() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (cont.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                String str[] = {Manifest.permission.CAMERA};
                this.requestPermissions(str, 6);
                return;
            }else{
                Intent intent = new Intent();
                intent.setClass(cont, Add.class);
                startActivity(intent);
            }
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_v_p_home, container, false);
    }

    ImageView we_now;
    TabLayout tabLayout;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        tabLayout=view.findViewById(R.id.tab_layout);
//        showTabTextAdapteIndicator(tabLayout);
        mViewPager = view.findViewById(R.id.home_vp);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout = view.findViewById(R.id.tab_layout);
        we_now = view.findViewById(R.id.img_weth);
        ConstraintLayout l = view.findViewById(R.id.tianwiweb);

        l.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(cont, WetherWeb.class);
                intent.putExtra("url", weburl);
                startActivity(intent);
            }
        });

        city = view.findViewById(R.id.city);
        temp_day = view.findViewById(R.id.temp_day);
        temp_now = view.findViewById(R.id.text_temp_now);
        initData();
        Button add = view.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestper();
            }
        });
        we = view.findViewById(R.id.text_we);
        getLocation();
        String loca_d = lo + "," + la;
        System.out.println(loca_d);
        System.out.println(loca);
        initWeather(loca_d);
//注意此处，getChild 嵌套
        mStVPTitleAdapter = new MyFragmentStVpTitleAdapter(getChildFragmentManager(), mFragmentList, titleList);
        mViewPager.setAdapter(mStVPTitleAdapter);
        mTabLayout.setupWithViewPager(mViewPager);//tab 适配页面
        showTabTextAdapteIndicator(mTabLayout);

    }

    public VPFragment vPfragment3;
    public VPFragment vPfragment1;
    public VPFragment vPfragment2;

    private void initData() {
        mFragmentList = new ArrayList<>();
        vPfragment1 = VPFragment.newInstance("客厅", R.drawable.ji1, this.cont, 0);
        vPfragment2 = VPFragment.newInstance("主卧", R.drawable.ji2, this.cont, 1);
        vPfragment3 = VPFragment.newInstance("次卧", R.drawable.ji3, this.cont, 2);
//        VPFragment vPfragment4 = VPFragment.newInstance("美",R.drawable.j4);
        mFragmentList.add(vPfragment1);
        mFragmentList.add(vPfragment2);
        mFragmentList.add(vPfragment3);
//        mFragmentList.add(vPfragment4);

        titleList = new ArrayList<>();
        titleList.add("客厅");
        titleList.add("主卧");
        titleList.add("次卧");
//        titleList.add("美");
    }
}